package com.xyz.timekeeper

import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.Alignment
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xyz.timekeeper.ui.theme.TimeKeeperApplicationTheme

import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.platform.LocalContext
import com.xyz.timekeeper.database.TimeKeeperDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import androidx.lifecycle.viewModelScope
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Assessment
import androidx.compose.material.icons.filled.Today
import androidx.compose.material3.Icon
import androidx.lifecycle.AndroidViewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.input.pointer.pointerInput
import com.xyz.timekeeper.database.TimeRecord
import kotlin.math.roundToInt

// 定义 MainActivity 类
class MainActivity : ComponentActivity() {

    // 覆盖 onCreate 方法
    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(MainActivity.TAG, "enter MainActivity.onCreate") // 记录日志
        super.onCreate(savedInstanceState) // 调用父类方法
        enableEdgeToEdge() // 启用边缘到边缘模式
        setContent {
            TimeKeeperApplicationTheme {
                MainScreen() // 设置主屏幕内容
            }
        }
    }

    // 覆盖 onStart 方法
    override fun onStart() {
        Log.d(MainActivity.TAG, "enter MainActivity.onStart") // 记录日志
        super.onStart() // 调用父类方法
    }

    // 覆盖 onResume 方法
    override fun onResume() {
        Log.d(MainActivity.TAG, "enter MainActivity.onResume") // 记录日志
        super.onResume() // 调用父类方法
    }

    // 覆盖 onPause 方法
    override fun onPause() {
        Log.d(MainActivity.TAG, "enter MainActivity.onPause") // 记录日志
        super.onPause() // 调用父类方法
    }

    // 覆盖 onStop 方法
    override fun onStop() {
        Log.d(MainActivity.TAG, "enter MainActivity.onStop") // 记录日志
        super.onStop() // 调用父类方法
    }

    // 覆盖 onDestroy 方法
    override fun onDestroy() {
        Log.d(MainActivity.TAG, "enter MainActivity.onDestroy") // 记录日志
        super.onDestroy() // 调用父类方法
    }

    // 覆盖 onRestart 方法
    override fun onRestart() {
        Log.d(MainActivity.TAG, "enter MainActivity.onRestart") // 记录日志
        super.onRestart() // 调用父类方法
    }

    // 定义伴生对象
    companion object {
        const val TAG = "timeKeeper" // 定义 TAG 常量
    }
}

// 定义 MainScreen 函数
@Composable
fun MainScreen() {
    Log.d(MainActivity.TAG, "enter MainScreen") // 记录日志
    val context = LocalContext.current // 获取当前上下文
    val viewModel: MainViewModel = viewModel(
        factory = ViewModelFactory(context.applicationContext as Application) // 创建 ViewModel
    )
    
    // 定义 selectedTabIndex 变量
    var selectedTabIndex by remember { mutableStateOf(0) }
    // 定义 tabs 列表
    val tabs = listOf("今天", "统计")
    
    // 定义 Scaffold 组件
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            NavigationBar {
                tabs.forEachIndexed { index, title ->
                    NavigationBarItem(
                        icon = { Icon(
                            if (index == 0) Icons.Default.Today else Icons.Default.Assessment,
                            contentDescription = title // 设置图标和内容描述
                        ) },
                        label = { Text(title) }, // 设置标签
                        selected = selectedTabIndex == index, // 设置选中状态
                        onClick = { selectedTabIndex = index } // 设置点击事件
                    )
                }
            }
        }
    ) { innerPadding ->
        when (selectedTabIndex) {
            0 -> ClockinScreen(
                modifier = Modifier.padding(innerPadding),
                isBorrowed = viewModel.isBorrowed,
                records = viewModel.records,
                onBorrowClick = { viewModel.toggleBorrowStatus() },
                viewModel = viewModel // 添加 viewModel 参数
            )
            1 -> StatisticsScreen(
                modifier = Modifier.padding(innerPadding),
                records = viewModel.records
            )
        }
    }
}

// 定义 ClockinScreen 函数
@Composable
fun ClockinScreen(
    modifier: Modifier = Modifier,
    isBorrowed: Boolean,
    records: List<TimeRecord>,
    onBorrowClick: () -> Unit,
    viewModel: MainViewModel // 添加 viewModel 参数
) {
    Log.d(MainActivity.TAG, "enter ClockinScreen") // 记录日志
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(top = 100.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(space = 16.dp)
    ) {
        // 定义 Button 组件
        Button(
            modifier = Modifier
                .width(200.dp)
                .height(80.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
                contentColor = MaterialTheme.colorScheme.onSurfaceVariant
            ),
            onClick = onBorrowClick // 设置点击事件
        ) {
            Text(
                if (isBorrowed) "还" else "借", // 设置按钮文本
                fontSize = 32.sp,
                color = Color.Black
            )
        }

        // 定义 LazyColumn 组件
        LazyColumn(modifier = Modifier.padding(top = 16.dp)) {
            // 定义 item 组件
            item {
                val today = java.text.SimpleDateFormat("EEEE", 
                    java.util.Locale.CHINA).format(java.util.Date()) // 获取当前星期
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .border(1.dp, Color.Gray),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = today, // 设置文本
                        modifier = Modifier.weight(1f),
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold
                    )
                }
            }

            // 定义 item 组件
            item {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .border(1.dp, Color.Gray),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text("次数", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                         style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold)) // 设置文本
                    Text("开始时间", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                         style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold)) // 设置文本
                    Text("结束时间", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                         style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold)) // 设置文本
                    Text("分钟", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                         style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold)) // 设置文本
                }
            }

            // 定义 items 组件
            itemsIndexed(records) { index, record -> // 修改：使用itemsIndexed获取索引
                var showDeleteDialog by remember { mutableStateOf(false) }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .border(1.dp, Color.Gray)
                        .pointerInput(Unit) {
                            detectTapGestures(
                                onTap = { /* 点击事件 */ },
                                onLongPress = { showDeleteDialog = true } // 长按事件触发删除对话框
                            )
                        },
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text( // 修改：使用索引生成序号
                        (index + 1).toString(), // 原为record.count.toString()
                        modifier = Modifier.weight(1f),
                        textAlign = TextAlign.Center
                    )
                    Text(record.displayStartTime, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                    Text(record.displayEndTime, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                    Text(record.duration, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                }

                // 删除对话框
                if (showDeleteDialog) {
                    AlertDialog(
                        onDismissRequest = { showDeleteDialog = false },
                        title = { Text("确认删除") },
                        text = { // 修改提示文本为动态显示次数
                            Text("是否删除第${index + 1}次记录？")
                        },
                        confirmButton = {
                            Button(onClick = {
                                showDeleteDialog = false
                                viewModel.deleteRecord(record) // 调用删除方法
                            }) {
                                Text("删除")
                            }
                        },
                        dismissButton = {
                            Button(onClick = { showDeleteDialog = false }) {
                                Text("取消")
                            }
                        }
                    )
                }
            }

            // 定义 item 组件
            item {
                val totalMinutes = records.sumOf { record ->
                    record.duration.replace("[^0-9]".toRegex(), "").toIntOrNull() ?: 0 // 计算总分钟数
                }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .border(1.dp, Color.Gray),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text("总计", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                         fontWeight = FontWeight.Bold) // 设置文本
                    Text("", modifier = Modifier.weight(1f), textAlign = TextAlign.Center) // 设置文本
                    Text("", modifier = Modifier.weight(1f), textAlign = TextAlign.Center) // 设置文本
                    Text(
                        "${totalMinutes}分钟",
                        modifier = Modifier.weight(1f),
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold // 设置文本
                    )
                }
            }
        }
    }
}

// 定义 StatisticsScreen 函数
@Composable
fun StatisticsScreen(
    modifier: Modifier = Modifier,
    records: List<TimeRecord>
) {
    Log.d(MainActivity.TAG, "enter StatisticsScreen") // 记录日志
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 总计统计
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text(
                    text = "总计统计",
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier.padding(bottom = 8.dp) // 设置文本
                )
                
                val totalDuration = records.sumOf {
                    it.duration.replace("[^0-9.]".toRegex(), "").toDoubleOrNull() ?: 0.0 // 计算总时长
                }.roundToInt() // 修改：将总时长四舍五入并取整

                // 定义 Row 组件
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text("总借用次数：${records.size}次") // 设置文本
                    Text("总用时：${totalDuration}分钟") // 修改：显示四舍五入后的总时长
                }
            }
        }

        // 每日统计
        Card(
            modifier = Modifier.fillMaxWidth(),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text(
                    text = "每日统计",
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                // 定义 LazyColumn 组件
                LazyColumn {
                    // 表头
                    item {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .border(1.dp, Color.Gray),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text("日期", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                                 style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold))
                            Text("次数", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                                 style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold))
                            Text("总时长", modifier = Modifier.weight(1f), textAlign = TextAlign.Center,
                                 style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold))
                        }
                    }

                    // 按日期分组的记录
                    val groupedRecords = records.groupBy {
                        it.startTime.split(" ")[0] // 提取日期部分
                    }.mapValues { entry ->
                        val count = entry.value.size
                        val duration = entry.value.sumOf {
                            it.duration.replace("[^0-9.]".toRegex(), "").toDoubleOrNull() ?: 0.0
                        }.roundToInt() // 修改：将总时长四舍五入并取整
                        Triple(entry.key, count, duration)
                    }

                    // 定义 items 组件
                    items(groupedRecords.toList().sortedByDescending { it.first }) { (date, stats) ->
                        var showDialog by remember { mutableStateOf(false) } // 添加状态变量控制对话框显示

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .border(1.dp, Color.Gray)
                                .clickable { showDialog = true }, // 添加点击事件
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            val displayDate = try {
                                val parsed = java.text.SimpleDateFormat("yyyy-MM-dd", 
                                    java.util.Locale.getDefault()).parse(date)
                                java.text.SimpleDateFormat("MM-dd", 
                                    java.util.Locale.getDefault()).format(parsed)
                            } catch (e: Exception) {
                                date
                            }
                            Text(displayDate, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                            Text("${stats.second}次", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                            Text("${stats.third}分钟", // 修改：显示四舍五入后的总时长
                                modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                        }

                        // 修改对话框内容
                        if (showDialog) {
                            AlertDialog(
                                onDismissRequest = { showDialog = false },
                                title = { Text(date) }, // 将 title 改为使用 date 变量
                                text = {
                                    Column {
                                        // 表头
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                            Text("次数", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                            Text("开始时间", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                            Text("结束时间", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                            Text("时长", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                        }

                                        // 数据行
                                        records.filter { it.startTime.startsWith(date) }.forEachIndexed { index, record -> // 修改：使用forEachIndexed获取索引
                                            Column(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(vertical = 4.dp)
                                            ) {
                                                Row(
                                                    modifier = Modifier.fillMaxWidth(),
                                                    horizontalArrangement = Arrangement.SpaceBetween
                                                ) {
                                                    Text((index + 1).toString(), modifier = Modifier.weight(1f), textAlign = TextAlign.Center) // 修改：使用索引生成序号
                                                    Text(record.displayStartTime, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                                    Text(record.displayEndTime, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                                    Text("${record.duration}分钟", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
                                                }
                                            }
                                        }
                                    }
                                },
                                confirmButton = {
                                }
                            )
                        }
                    }
                }
            }
        }
    }
}

// 定义 MainViewModel 类
class MainViewModel(application: Application) : AndroidViewModel(application) {

    // 定义 dateFormat 变量
    private val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())
    // 定义 dateTimeFormat 变量
    private val dateTimeFormat = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
    // 定义 timeFormat 变量
    private val timeFormat = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
    
    // 定义 _isBorrowed 变量
    private val _isBorrowed = mutableStateOf(false)
    val isBorrowed: Boolean
        get() = _isBorrowed.value

    // 定义 _records 变量
    private val _records = mutableStateOf<List<TimeRecord>>(emptyList())
    val records: List<TimeRecord>
        get() = _records.value

    // 定义 database 变量
    private val database = TimeKeeperDatabase.getDatabase(application)
    // 定义 dao 变量
    private val dao = database.timeRecordDao()

    // 初始化块
    init {
        Log.d(MainActivity.TAG, "enter MainViewModel.init") // 记录日志
        loadTodayRecords() // 加载今日记录
    }

    // 定义 loadTodayRecords 函数
    private fun loadTodayRecords() {
        Log.d(MainActivity.TAG, "enter MainViewModel.loadTodayRecords") // 记录日志
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val today = dateFormat.format(java.util.Date()) // 获取当前日期
                val todayRecords = dao.getRecordsByDate(today) // 获取今日记录
                _records.value = todayRecords // 更新记录
            }
        }
    }

    // 定义 toggleBorrowStatus 函数
    fun toggleBorrowStatus() {
        Log.d(MainActivity.TAG, "enter MainViewModel.toggleBorrowStatus") // 记录日志
        viewModelScope.launch {
            val currentDate = java.util.Date() // 获取当前日期
            val calendar = java.util.Calendar.getInstance() // 创建日历实例
            calendar.time = currentDate // 设置当前时间

            if (!_isBorrowed.value) {
                // 借
                calendar.add(java.util.Calendar.SECOND, 5) // 增加 5 秒
                val adjustedDate = calendar.time // 获取调整后的时间
                val fullDateTime = dateTimeFormat.format(adjustedDate) // 格式化完整日期时间
                val timeOnly = timeFormat.format(adjustedDate) // 格式化时间
                Log.d(MainActivity.TAG, "借的实际时间: ${dateTimeFormat.format(currentDate)}, 记录到数据库的时间: $fullDateTime") // 新增日志打印
                val newRecord = TimeRecord(
                    id = 0,
                    count = records.size + 1,
                    startTime = fullDateTime,  // 保存完整时间用于计算
                    displayStartTime = timeOnly,  // 显示用的时间
                    endTime = "",
                    displayEndTime = "",
                    duration = "0"
                )
                withContext(Dispatchers.IO) {
                    dao.insert(newRecord) // 插入新记录
                    loadTodayRecords() // 加载今日记录
                }
            } else {
                // 还
                calendar.add(java.util.Calendar.SECOND, -5) // 减少 5 秒
                val adjustedDate = calendar.time // 获取调整后的时间
                val fullDateTime = dateTimeFormat.format(adjustedDate) // 格式化完整日期时间
                val timeOnly = timeFormat.format(adjustedDate) // 格式化时间
                Log.d(MainActivity.TAG, "还的实际时间: ${dateTimeFormat.format(currentDate)}, 记录到数据库的时间: $fullDateTime") // 新增日志打印
                records.lastOrNull()?.let { lastRecord ->
                    val updatedRecord = lastRecord.copy(
                        endTime = fullDateTime,
                        displayEndTime = timeOnly,
                        duration = calculateDuration(lastRecord.startTime, fullDateTime) // 计算持续时间
                    )
                    withContext(Dispatchers.IO) {
                        dao.update(updatedRecord) // 更新记录
                        loadTodayRecords() // 刷新记录列表
                    }
                }
            }
            _isBorrowed.value = !_isBorrowed.value // 切换借还状态
        }
    }

    // 定义 calculateDuration 函数
    private fun calculateDuration(startTime: String, endTime: String): String {
        Log.d(MainActivity.TAG, "enter MainViewModel.calculateDuration") // 记录日志
        return try {
            val format = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
            val start = format.parse(startTime) ?: return "0" // 解析开始时间
            val end = format.parse(endTime) ?: return "0" // 解析结束时间
            val diffMinutes = ((end.time - start.time) / (1000.0 * 60)).toInt() // 计算分钟数
            diffMinutes.toString() // 返回分钟数字符串
        } catch (e: Exception) {
            "0" // 返回默认值
        }
    }

    // 新增删除方法
    fun deleteRecord(record: TimeRecord) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                dao.delete(record) // 调用 DAO 删除记录
                loadTodayRecords() // 刷新记录列表
            }
        }
    }
}

// 定义 ViewModelFactory 类
class ViewModelFactory(private val application: Application) : ViewModelProvider.Factory {

    // 覆盖 create 方法
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        Log.d(MainActivity.TAG, "enter ViewModelFactory.create") // 记录日志
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return MainViewModel(application) as T // 创建 MainViewModel 实例
        }
        throw IllegalArgumentException("Unknown ViewModel class") // 抛出异常
    }
}

// 定义 ClockinPreview 函数
@Preview(showBackground = true)
@Composable
fun ClockinPreview() {
    Log.d(MainActivity.TAG, "enter ClockinPreview") // 记录日志
    TimeKeeperApplicationTheme {
        ClockinScreen(
            isBorrowed = false,
            records = emptyList(),
            onBorrowClick = {}, // 设置预览内容
            viewModel = MainViewModel(Application()) // 新增：模拟ViewModel实例
        )
    }
}